import { login, logout } from '@/api/user'
import storage from '@/utils/storage'

const user = {
  state: {
    username: '',
    nickname: '',
    token: ''
  },
  getters: {
    isLogin(state) {
      return state.userName !== '' && state.token !== ''
    }
  },
  mutations: {
    SAVE_USERNAME(state, username) {
      state.username = username
    },
    SAVE_NICKNAME(state, nickname) {
      state.nickname = nickname
    },
    SAVE_TOKEN(state, token) {
      state.token = token
    }
  },
  actions: {
    LOGIN({ commit }, user) {
      return new Promise((resolve) => {
        login(user).then((res) => {
          // 需要将获取的数据保存起来
          commit('SAVE_USERNAME', res.data.ydlUser.userName)
          commit('SAVE_NICKNAME', res.data.ydlUser.nickName)
          commit('SAVE_TOKEN', res.data.token)
          storage.saveSessionObject('loginUser', res.data)
          resolve(res)
        })
      })
    },
    LOGOUT({ commit }) {
      return new Promise((resolve) => {
        logout().then((res) => {
          // 需要将获取的数据保存起来
          commit('SAVE_USERNAME', '')
          commit('SAVE_NICKNAME', '')
          commit('SAVE_TOKEN', '')
          storage.remove('loginUser')
          resolve(res)
        })
      })
    },
    RECOVERY_USER({ commit }) {
      // 从storage中获取数据
      let loginUser = storage.getSessionObject('loginUser')
      if (loginUser) {
        commit('SAVE_USERNAME', loginUser.ydlUser.userName)
        commit('SAVE_NICKNAME', loginUser.ydlUser.nickName)
        commit('SAVE_TOKEN', loginUser.token)
      }
    }
  }
}

export default user
